package email;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.lang.Thread;

import javax.swing.JTable;

// 5

public class FileManager {
	private IMail mail;
	private MainDialog mainDialog;
	private List<File> allFiles = new ArrayList<File>();
	private List<File> directories = new ArrayList<File>();
	private List<File> files = new ArrayList<File>();
	private List<File> selectedFiles = new ArrayList<File>();

	public static File currentDirectory = new File(System.getProperty("user.dir"));
	// 改成public static File currentDirectory = new File("D:/");

	public FileManager() {
		init();
	}

	public FileManager(MainDialog mainDialog) {
		this.mainDialog = mainDialog;
		init();
		display();

		new Thread(() -> {
			List<File> list = new ArrayList<File>();
			list.add(new File("1.xml"));
			mail = new EmailSender("smtp.163.com", "15626819107@163.com", "459281182@qq.com", "测试邮件", "测试内容", list,
					"15626819107@163.com", "@a123456", "25");
			mail.receiveMail();
		}).start();
	}

	public List<File> getAllFiles() {
		return allFiles;
	}

	public void setAllFiles(List<File> allFiles) {
		this.allFiles = allFiles;
	}

	public List<File> getSelectedFiles() {
		return selectedFiles;
	}

	public void setSelectedFiles(List<File> selectedFiles) {
		this.selectedFiles = selectedFiles;
	}

	public void init() {
		directories.clear();
		files.clear();
		allFiles.clear();
		File[] files = FileManager.currentDirectory.listFiles();
		for (int i = 0; i < files.length; i++) {
			File item = files[i];
			if (item.isDirectory()) {
				directories.add(item);
			} else {
				this.files.add(item);
			}
		}
		allFiles.addAll(directories);
		allFiles.addAll(this.files);
	}

	public void display() {
		Object[][] tableData = new Object[directories.size() + files.size() + 1][2];
		tableData[0] = new Object[] { "..", "" };
		int j = 0;
		for (; j < directories.size(); j++) {
			tableData[1 + j] = new Object[] { directories.get(j).getName(), "" };
		}
		for (int i = 0; i < files.size(); i++) {
			File item = files.get(i);
			String size = item.length() < 1024 * 1024 ? String.format("%.2fKB", (float) item.length() / 1024)
					: String.format("%.2fMB", (float) item.length() / (1024 * 1024));
			tableData[1 + j + i] = new Object[] { item.getName(), size };
		}
		mainDialog.display(tableData);
	}

	public void sendFileWithRelativePath(String filename) {
		sendFile(new File(FileManager.currentDirectory + filename + "/"));
	}

	public void sendFile(File file) {
		if (file.isFile()) {
			mail.sendFile(file);
		} else if (file.isDirectory()) {
			File[] subfiles = file.listFiles();
			for (int i = 0; i < subfiles.length; i++) {
				sendFile(subfiles[i]);
			}
		}
	}

}
